<!DOCTYPE html>
<html>

	<head>
		<meta charset="utf-8">
		<title></title>
	</head>

	<body>
	</body>
	<script>
		(function() {
			var arr = [1, 2, 3];
			var obj = {};

			var test = function() {
				var b = 5;
				for(var i = 0; i < arr.length; i++) {
					(function(i) { //传不传i很大区别
						obj[i] = function() {
							console.log(i + ',' + b)
						};
					})(i); //i作为参数传给立即调用函数
				}
				return function() {
					b++;
				}
			};
			var addB = test();
			var fn0 = obj[0];
			var fn1 = obj[1];
			var fn2 = obj[2];

			fn0();      //0,5
			fn1();		//1,5
			fn2();		//2,5

			addB();		//b++
			fn0();		//0,6
		});

		(function() {

			var test = function() {

				var i = 0;

				setTimeout(function() {
					console.log(i);          //1
				}, 1000);

				return function() {
					console.log(i);
					i++;
				}
			}

			var fn = test();
			fn();		//0
			fn();		//1
		});

		//解释了第一题为什么最后b会为6，因为在里层中没有var，所以用的是外面var的i
		(function() {
			var test = function() {

				var i = 0;

				setTimeout(function() {
					console.log(i);
				}, 1000)

				var fn1 = function() {
					setTimeout(function() {
						i++;
					}, 500);
				}

				fn1();
			}
			test();
		});
		
		//循环后各个作用域被抽离了，各自独立了。所以一个作用域的变量变不影响其他作用域的变量
		(function() {
			var arr = [1, 2, 3];
			var obj = {};
			var test = function() {
				for(var i = 0; i < arr.length; i++) {
					(function(i) {
						setTimeout(function(){
							i = 8;
						},1000);
                        // setTimeout(function(){alert(i);},1000);
                        obj[i] = function() {
							console.log(i++);
						};
					})(i); //i作为参数传给立即调用函数
				}
			};
			test();
			var fn0 = obj[0];
			var fn1 = obj[1];
			var fn2 = obj[2];

			fn0(); 
			fn0(); 
			fn0(); 
			setTimeout(function(){
				fn0();    
			},2000);
			
			fn1(); 
			fn1(); 
			setTimeout(function(){
				fn1();     
			},3000);
			
			// 两次fn2()访问同一个内存中的i值
			// fn2(); //2
			// fn2(); //3
		})();
		
	</script>

</html>